<template>
  <el-button type="primary" @click="dialogVisible = true">创建项目</el-button>
  <el-dialog v-model="dialogVisible" title="创建项目" width="600px">
    <el-form ref="formRef" :model="form" label-width="100px">
      <el-form-item label="业务类型">
        <el-select style="width: 100%;" v-model="form.busType">
          <el-option :value="1" label="自然人代开"></el-option>
          <el-option :value="2" label="委托代征"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="业务标题">
        <el-input v-model="form.name" />
      </el-form-item>
      <el-form-item label="所属行业">
        <el-cascader style="width: 100%;" v-model="form.industry" :show-all-levels="false" :options="industryOptions || []" />
      </el-form-item>
      <el-form-item label="项目类型">
        <el-radio-group v-model="form.classify">
          <el-radio :label="1">抢单</el-radio>
          <el-radio :label="2">派单</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="项目总金额">
        <template v-if="form.classify === 1">
          <el-col :span="11">
            <el-input-number style="width: 100%;" controls-position="right" v-model="form.cost" />
          </el-col>
          <el-col style="text-align: center;" :span="2">~</el-col>
          <el-col :span="11">
            <el-input-number style="width: 100%;" controls-position="right" v-model="form.costMax" />
          </el-col>
        </template>
        <el-input-number style="width: 100%;" controls-position="right" placeholder="请输入项目总金额" v-else v-model="form.costMax" />
      </el-form-item>

      <template v-if="form.classify === 1">
        <el-form-item label="用工人数">
          <el-input-number style="width: 100%;" placeholder="请输入项目用工人数" v-model="form.limitNum" :min="0" :max="100" />
        </el-form-item>

        <el-form-item label="截至日期">
          <el-date-picker value-format="YYYY-MM-DD HH:mm:ss" placeholder="请输入截至日期" v-model="form.jiezhiDate" />
        </el-form-item>
      </template>

      <el-form-item label="项目内容">
        <el-input
          :rows="10"
          placeholder="
                    请输入项目职责、项目要求等，至少20字，建议使用短句并分条列出，如下：
                    项目职责：
                    1、.....
                    2、.....
                    项目要求：
                    1、.....
                    2、.....
                    "
          type="textarea"
          v-model="form.proContent"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button :loading="loading" @click="onSubmit(0)">保存</el-button>
        <el-button type="primary" :loading="loading" @click="onSubmit(1)">保存并发布</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { Method } from 'axios';
import { TaskInfo } from '../types';


interface TreeNode {
  value: number | string;
  label: string;
  children?: TreeNode[]; // 使用 ? 表示children是可选的
}

function findNodeById(tree: TreeNode[], value: number | string): TreeNode | null {
  for (const node of tree) {
    if (node.value == value) {
      return node;
    }
    if (node.children && node.children.length > 0) {
      const foundNode = findNodeById(node.children, value);
      if (foundNode) {
        return foundNode;
      }
    }
  }
  return null;
}


const { data: industryOptions } = useRequest('/system/industry/selList', 'GET', {
  }, { immediate: true })

const dialogVisible = ref(false)

const loading = ref(false)

interface FormData {
    proContent: string;
    name: string;
    cost: number;
    costMax: number;
    busType: 1 | 2 | '';
    classify: string | number;
    industry: string;
    limitNum: number,
    jiezhiDate: string;
    id: string;  // 项目id
}

const form = reactive<FormData>({
    proContent: '',
    name: '',
    cost: 0,
    costMax: 0,
    busType: '',
    classify: 1,
    industry: '',
    limitNum: 0,
    jiezhiDate: '',
    id: '',  // 项目id
})

const formRef = ref<ElFormInstance>();



const onSubmit = (taskStatus: 0 | 1 = 0) => {
    formRef?.value!.validate(async(valid) => {
        if (valid) {
            loading.value = true
            const [,nodeValue] = form.industry || []
            const node = findNodeById(industryOptions.value as TreeNode[], nodeValue as string)

            const submitData = {
              ...form,
              industryName: node?.label,
              industry: node?.value,
              sydId: 1,
              merId: 3,
              merNo: 'A10109-B10534-M32085',
              sydNo: 'S10128',
              status: 1,
              taskStatus
            }

            const { id: taskId } = submitData
            let url: string, requestMethod: Method;
            if (taskId) {
              url = '/payment/task/edit'
              requestMethod = 'PUT'
            } else {
              url = '/payment/task/add';
              requestMethod = 'POST'
            }

            const reponse = await useRequest(url, requestMethod, { data: submitData }, { immediate: true })
            loading.value = false
            if (reponse?.data) {
              dialogVisible.value = true
            }

        }
    })
}

defineExpose({
  onEdit: (row: TaskInfo) => {
    dialogVisible.value = true
    Object.keys(form).forEach((key) => {
      form[key] = row[key]
    })
  }
})

onMounted(() => {
  const data = useRequest('/payment/proInfo/selBtByMs', 'GET', {
    params: {
      sydId: 1,
      merId: 1
    }
  }, { immediate: true })

})
</script>
<style scoped>
.dialog-footer button:first-child {
    margin-right: 10px;
}
</style>
